<?php
Framework::needs("engine.Path");
Framework::needs("engine.Logger");
Framework::needs("engine.Session");
Framework::needs("engine.Render");

class SystemController {
	private $authmod;
	private $initmod;
	private $logenabled=false;
	private $render;
	
	private static $currmod="";
	
	public static function getCurrentModName(){
		return trim(self::$currmod);
	}
	
	public function __construct($authmod,$initmod) {
		$this->authmod=$authmod;
		$this->initmod=$initmod;
		$this->headers();
	}
	
	private function headers() {
		header('Content-type: text/html;charset='.SYSTEM_ENCODING);
	}
	
	public function enableLogger(){
		$this->logenabled=true;
	}

	public function control(){
		if(isset($_GET['mod'])){
			self::$currmod=$_GET['mod'];
			if(Session::isAuth()) {
				$this->load($_GET['mod']);
				$this->log(Logger::NOTICE,"Navigating on ".$_GET['mod']." module");
			} else {
				self::$currmod=$this->authmod;
				$this->load($this->authmod);
				$this->log(Logger::UNAUTORIZED,"Tried to navigate on ".$_GET['mod']." module without login");
			}
		} else {
			if(Session::isAuth()) {
				self::$currmod=$this->initmod;
				$this->load($this->initmod);
				$this->log(Logger::NOTICE,"Navigating on initial module (".$this->initmod.")");
			} else {
				self::$currmod=$this->authmod;
				$this->load($this->authmod);
				$this->log(Logger::NOTICE,"Navigating on authentication module (".$this->authmod.")");
			}
		}
	}
	private function load($module){
		$modfile=Path::getPathFromModuleName($module).DIRECTORY_SEPARATOR.$module.".class.php";
		//die($modfile);
		if(file_exists($modfile)) {
			include($modfile);
			$class=$module;
			$mod=new $class($_POST,$_GET);
			$this->render=$mod->toRender();
		} else {
			$this->log(Logger::HUMAN_CORRUPTION,"Tried to browse on '".$module."' module, but this module not exists");
			die("Module not exists!");
		}
	}
	private function log($event,$string) {
		if($this->logenabled)
			Logger::write($event,$string);
	}
	public function show(){
		include SYSTEM_PATH.'/system/main/Main.class.php';
		$tmp=new Main();
		$rmaster=$tmp->toRender();
		$rmaster->add($this->render->toHTML(),'main');
		$rmaster->flush();		
	}
}
?>